package com.tinem.platform.web.gateway.filter;

import cn.hutool.core.collection.CollUtil;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.web.gateway.util.GatewayUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className LogMdcGatewayFilterFactory
 * @description TODO
 * @site 
 * @company 
 * @create 2020-07-03 15:56
 */
@Component
@Slf4j
public class LogMdcGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
    @Resource
    io.opentracing.Tracer tracer;
    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) ->{
            String gateway_request_id = GatewayUtil.getReq(exchange);
            String client_request_id = GatewayUtil.getApiReq(exchange);
            String opentracing_id = tracer.activeSpan().context().toTraceId();
            String jwt = GatewayUtil.getJwt(exchange);
            String jit = GatewayUtil.getJit(exchange);
            MDC.put(GatewayHeadName.X_PLATFORM_GATEWAY_REQUEST_ID,gateway_request_id);
            MDC.put(GatewayHeadName.X_PLATFORM_GATEWAY_CONTEXT_JTI,jit);
            log.info("request gateway fastlog gateway_request_id: [{}];client_request_id: [{}];opentracing_id: [{}];jit: [{}]; jwt: [{}]"
                    ,gateway_request_id
                    ,client_request_id
                    ,opentracing_id
                    ,jit
                    ,jwt
            );
            if(log.isDebugEnabled()){
                exchange.getRequest().getHeaders().entrySet().forEach(e ->
                    log.debug("http head: {}:{}",e.getKey(), CollUtil.join(e.getValue(),","))
                );
            }
            return chain.filter(exchange);
        };
    }
}
